package com.example.dao;

import com.example.entity.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 用户数据访问层
 */
@Repository
public class UserDao {

    @Resource
    private JdbcTemplate jdbcTemplate;

    /**
     * 根据ID查询用户
     */
    public User findById(Long id) {
        String sql = "SELECT id, username, password, age, email FROM t_user WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{id}, new UserRowMapper());
    }

    /**
     * 查询所有用户
     */
    public List<User> findAll() {
        String sql = "SELECT id, username, password, age, email FROM t_user";
        return jdbcTemplate.query(sql, new UserRowMapper());
    }

    /**
     * 保存用户
     */
    public int save(User user) {
        String sql = "INSERT INTO t_user(username, password, age, email) VALUES(?, ?, ?, ?)";
        return jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), user.getAge(), user.getEmail());
    }

    /**
     * 用户实体映射器
     */
    private static class UserRowMapper implements RowMapper<User> {
        @Override
        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            User user = new User();
            user.setId(rs.getLong("id"));
            user.setUsername(rs.getString("username"));
            user.setPassword(rs.getString("password"));
            user.setAge(rs.getInt("age"));
            user.setEmail(rs.getString("email"));
            return user;
        }
    }
} 